# coding=utf-8
"""
    初始化 flask app :
"""
import json
import logging
import uuid
from json import JSONDecodeError

from flask import Flask, g, request
from config import conf
from controller.ocr import ocr_bp
from utils.base.base_res import base_res
from utils.do_logger import OcrLog, TraceIdFilter


# @Time    :  2024-10-29 17:11:51
# @Author  :  jiangtong
# @Email   :  gingerqgyy@outlook.com
# @Project :  flask_ocr
# @File    :  __init__.py

# 初始化 flask app ：
def create_app(conf_name):
    # 初始化 app :
    _app = Flask(__name__)

    # 禁用 werkzeug 的日志打印 :
    logging.getLogger('werkzeug').setLevel(logging.ERROR)

    # 加载配置文件 : ( dev / prod )
    conf_name = conf_name.strip()
    conf_name = conf_name if conf_name in conf else 'prod'
    _app.config.from_object(conf[conf_name])

    # 设置 Flask 的日志格式
    log_format = '%(asctime)s [%(trace_id)s] %(levelname)s %(process)d --- [%(threadName)s] %(name)s %(lineno)d : %(message)s'
    logging.basicConfig(format=log_format)

    # 配置日志 :
    # OcrLog(_app)
    OcrLog.configure_logging(_app)
    _app.logger.addFilter(TraceIdFilter())

    # 注册 before_request 钩子,  # 生成 trace_id
    @_app.before_request
    def before_request():
        g.trace_id = str(uuid.uuid4())

    # 注册 404 错误处理
    @_app.errorhandler(404)
    def not_found(error):
        response = base_res(result=None, code='REQUEST_RESOURCE_NOTFOUND', message='请求资源未找到！', error_code=None, trace_id=g.trace_id)
        response.status_code = 404
        return response

    @_app.errorhandler(405)
    def method_not_allowed(e):
        response = base_res(result=None, code='REQUEST_METHOD_NOT_SUPPORTED', message='请求方法不支持！', error_code=None, trace_id=g.trace_id)
        response.status_code = 405
        return response

    # 注册 after_request 钩子，记录响应信息
    @_app.after_request
    def after_request(response):
        try:
            res = json.loads(response.data)
        except JSONDecodeError:
            res = base_res(result=None, code='JSON_DATA_ERROR', message='数据处理异常！', error_code=None, trace_id=g.trace_id)
        _app.logger.info(f'Response Info: {res}')
        return response

    # 注册蓝图 :
    _app.register_blueprint(ocr_bp, url_prefix='/api/yft')

    return _app
